<template>

  <div class="panel">
    <el-form v-loading="!operateData.dataReady" :model="operateData.post" class="demo-form-inline" label-width="100px">

      <el-form-item label="主体" class="content-main">
        <upload-oss list-type="picture-card" :limit="9" :imageUrl="operateData.imageUrlList" :beforeUpload="(file)=>operateFn.beforeUpload(file)" @upload="operateFn.afterUpload"></upload-oss>
      </el-form-item>

      <el-form-item label="备注">
        <el-input v-model="operateData.post.remark" type="textarea" rows="5"></el-input>
      </el-form-item>

      <el-form-item label="适用版本">
        <el-checkbox-group v-model="operateData.post.guideVersions">
          <template v-for="(item,index) in operateData.versionList" :key="index">
            
            <el-checkbox style="display:block;" :label="item.osType+'-'+item.version" v-if="!item.isUsed || operateData.backupInitVersion.includes(item.osType+'-'+item.version)">
              <span>{{item.osType}}</span>
              <span style="margin:0 8px;">{{item.channel}}</span>
              <el-tag>{{item.version}}</el-tag>
            </el-checkbox>
          </template>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item style="text-align:center">
        <template v-if="operateData.dataReady">
          <el-button type="primary" plain @click="operateFn.submitPre">提交</el-button>
        </template>
      </el-form-item>
    </el-form>
  </div>

</template>

<script>
export default {
  name: "guideOperate",
};
</script>
<script setup>
import { reactive, ref, watchEffect } from "vue";
import { getGuideDetail, editGuide, addGuide } from "@/api/material.js";
import { getVersionStatusList } from "@/api/config.js";
import { onBeforeRouteUpdate, useRouter } from "vue-router";
// import imageViewer from "@/components/imageViewer";
import { ElMessage } from "element-plus";
import { useStore } from "@/store";
import UploadOss from "@/components/AliOSS";

const store = useStore();
const router = useRouter();
const params = ref({});
const query = ref({});
watchEffect(()=>{
  params.value = router.currentRoute.value.params;
})
watchEffect(()=>{
  query.value = router.currentRoute.value.query;
})

// 新增和编辑
const { $data: operateData, $fn: operateFn } = (() => {
  const backup = {
    query: {
      endpoint: "pico",
      page: 1,
      pageSize: 1000,
    },
    post: {
      remark: "",
      guideImages: [],
      guideVersions: [],
    },
    fileData: [],
    versionMap: new Map(),
  };
  const $data = reactive({
    isEdit: !!params.value.id,
    backupInitVersion: [],
    post: {
      ...backup.post,
    },
    dataReady: false, //数据是否已拿到
    versionList: [],

    imageUrlList: undefined, //上传的图片列表 [{url:'xxx'},{url:'xxx'},...]
  });

  const $fn = {
    getDetails() {
      console.log("guide operate:",params.value.id);
      if (!params.value.id) return;
      $data.dataReady = false;
      getGuideDetail(params.value.id).then((res) => {
        console.log(params.value.id, "res:", res);
        if (res.code === 0) {
          let data = res.data || {};
          $data.dataReady = true;
          $data.post.remark = data.remark;
          $data.post.guideVersions = data.versions;//["IOS-1.0.1","ANDROID-1.0.1"]
          $data.imageUrlList = (() => {
            let imgs = [];
            for (let url of res.data.images || []) {
              imgs.push({ url });
            }
            return imgs;
          })();
          $data.backupInitVersion = [...data.versions];
        }
      });
    },
    getVersions() {
      getVersionStatusList().then((res) => {
        console.log("version list:", res);
        if (res.code === 0) {
          $data.versionList = res.data || [];
          for (let prop of $data.versionList) {
            backup.versionMap.set(prop.osType+'-'+prop.version, { ...prop });
          }
        }
      });
    },
    // 提交
    submitPre() {
      if (!$data.imageUrlList || $data.imageUrlList.length === 0) {
        ElMessage.warning("请上传图片！");
        return;
      }
      $fn.submitData();
    },
    submitData() {
      // 数据验证
      let req = {
        ...$data.post,
        guideImages: $data.imageUrlList.map((item) => ({ imageUrl: item.url })),
        guideVersions: $data.post.guideVersions.map((typeVersion) => {
          let item = backup.versionMap.get(typeVersion)||{};
          return {
            versionId: item.appVersionId,
            osType: item.osType,
            versionName: item.version,
          }
        }),
      };
      console.log("req data:", { ...req });
      if ($data.isEdit) {
        console.log("req:", { ...req, id: params.value.id });
        // return;
        editGuide({ ...req, id: params.value.id }).then((res) => {
          if (res.code === 0) {
            ElMessage.success("修改成功！");
            store
              .dispatch("tagsView/delView", { ...router.currentRoute.value })
              .then(() => {
                router.replace({ path: "/material/guideList" });
              });
          }
        });
      } else {
        console.log("req:", req);
        // return;
        addGuide(req).then((res) => {
          if (res.code === 0) {
            ElMessage.success("添加成功！");
            store
              .dispatch("tagsView/delView", { ...router.currentRoute.value })
              .then(() => {
                router.replace({ path: "/material/guideList" });
              });
          }
        });
      }
    },
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        const size = file.size / 1024;
        if (size > 1024) {
          ElMessage.error("图片大小不能超过 1 MB！");
          reject();
          return;
        }
        resolve();
      });
    },
    afterUpload(list) {
      if (!list || !list[0]) {
        $data.post.guideImages = undefined;
        $data.imageUrlList = undefined;
        return;
      }
      $data.imageUrlList = [];
      for (let prop of list || []) {
        $data.imageUrlList.push({
          url: prop.showUrl
            ? "https://img.qumoyugo.com" + prop.showUrl
            : prop.url,
        });
      }
    },
  };

  $fn.getVersions();
  return {
    $data,
    $fn,
  };
})();

function init(){
  if (operateData.isEdit) {
    operateFn.getDetails();
  } else {
    operateData.dataReady = true;
  }
}
init();

// 从相同路由进入（不同参数），如/a/b/1 => /a/b/2
onBeforeRouteUpdate((to, from, next) => {
  params.value.id = to.params.id;
  init();
  next();
});
</script>

<style scoped lang="scss">
.panel {
  background-color: #ffffff;
  padding: 12px;
  border-radius: 8px;
}
.isEmpty {
  color: rgb(172, 172, 172);
}
.content-main {
  .blockBg {
    display: inline-block;
    vertical-align: top;
  }
  .imgBg {
    display: inline-block;
  }
}
</style>